package application.mvc.biz.archive;

import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;

import application.common.model.Store;
import application.common.model.StoreMap;
import application.common.model.StoreUser;
import application.common.render.Archive;
import application.common.render.HttpClientResult;
import application.common.ui.ArchiveDialog;
import application.common.ui.ProgressStage;
import application.common.util.HttpUtil;
import application.common.util.LayerUtil;
import application.common.util.RouteUtil;
import application.common.util.ShiroUtil;
import javafx.animation.Animation;
import javafx.animation.Interpolator;
import javafx.animation.KeyFrame;
import javafx.animation.RotateTransition;
import javafx.animation.Timeline;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.Pane;
import javafx.util.Duration;
import net.sf.json.JSONObject;
import javafx.concurrent.Task;

public class ArchiveController implements Initializable {

	private final Log log = Log.getLog(getClass());

	
	@FXML
	private Label headerLabel;
	
	@FXML
	private Label copyrightLabel;
	
	@FXML
	private ImageView portraitImageView;
	
	@FXML
	private Label usernameLabel;
	
	@FXML
	private Label roleNameLabel;
	
	@FXML
	private ScrollPane archiveListScrollPane;

	@FXML
	private Button settingBtn;
	
	@FXML
	private Pane noArchivePane;
	
	@FXML
	private FlowPane archiveListPane;

	@FXML
	private Pane timerOutLinePane;

	@FXML
	private Pane timerInLinePane;
	
	private boolean isDestroy;

	@FXML
	private Label timerLabel;
	private Timeline animation;
	private RotateTransition rotateTransitionOut;
	private RotateTransition rotateTransitionIn;

	private ObservableList<ArchivePanel> dataList = FXCollections.observableArrayList();
	
	private ArchiveController controller;
	public ArchiveController() {
		this.controller=this;
	}

	public void initialize(URL arg0, ResourceBundle arg1) {
		
		headerLabel.setText(ShiroUtil.getSoftName());
		copyrightLabel.setText(ShiroUtil.getCopyright());
		
		if(ShiroUtil.getUser().getRoleKey().contains("setting")) {
			settingBtn.setVisible(true);
		}
		else {
			settingBtn.setVisible(false);
		}
		portraitImageView.setImage(ShiroUtil.getUser().getPortrait());
		usernameLabel.setText(ShiroUtil.getUser().getName());
		roleNameLabel.setText(ShiroUtil.getUser().getRoleName());
		
		log.error("卷宗列表1！");

		
		ProgressStage.of(RouteUtil.mainStage, new Task<Void>() {
			@Override
			protected Void call() throws Exception {
				log.error("---call---");
				List<StoreMap> storeMaps = StoreMap.dao.find("select * from " + StoreMap.TABLE_NAME + " order by sort asc ");
		    	String _sql="select * from "+Store.TABLE_NAME+" where 1=1 ";
		    	if(!ShiroUtil.getUser().getRoleKey().contains("all")) {
		    		_sql+=" and id in (select storeId from "+StoreUser.TABLE_NAME+" where userId='"+ShiroUtil.getUser().getId()+"') ";
				}
	    		_sql+=" ORDER BY field5 asc ";
				List<Store> stores=Store.dao.find(_sql);
				
				if(stores!=null && stores.size()>0) {
					log.error("---stores!=null && stores.size()>0---");
					for (Store store : stores) {
						dataList.add(new ArchivePanel(controller,store,storeMaps));
					}
					log.error("---ArchivePanel---");
					Platform.runLater(new Runnable() {
					    public void run() {
					    	log.error("---archiveListScrollPane---");
							archiveListScrollPane.setVisible(true);
							noArchivePane.setVisible(false);
							archiveListPane.getChildren().addAll(dataList);
							log.error("---archiveListScrollPane-（end）---");
					    }
					});
				}else {
					log.error("---null---");
					Platform.runLater(new Runnable() {
					    public void run() {
					    	log.error("---null---");
							archiveListScrollPane.setVisible(false);
							noArchivePane.setVisible(true);
							archiveListPane.getChildren().addAll(dataList);
							log.error("---null-end---");
					    }
					});
				}
				if(!isDestroy) {
					log.error("---isDestroy---");
					rotateTransitionOut = new RotateTransition(Duration.seconds(10), timerOutLinePane);
					rotateTransitionOut.setFromAngle(0);
					rotateTransitionOut.setToAngle(360);
					rotateTransitionOut.setByAngle(360); // 设置旋转的角度
					rotateTransitionOut.setCycleCount(Animation.INDEFINITE); // 设置旋转次数，我们需要旋转无数次
					rotateTransitionOut.setInterpolator(Interpolator.LINEAR);
					rotateTransitionOut.play();

					rotateTransitionIn = new RotateTransition(Duration.seconds(10), timerInLinePane);
					rotateTransitionIn.setFromAngle(360);
					rotateTransitionIn.setToAngle(0);
					rotateTransitionIn.setByAngle(360); // 设置旋转的角度
					rotateTransitionIn.setCycleCount(Animation.INDEFINITE); // 设置旋转次数，我们需要旋转无数次
					rotateTransitionIn.setInterpolator(Interpolator.LINEAR);
					rotateTransitionIn.play();
					log.error("---rotateTransitionIn---");
					startCountDown();
					log.error("---startCountDown---");
				}
				return null;
			}
		}, "查询中...").show();
	}

	public void exit(ActionEvent event) {
		if(!isDestroy) {
			isDestroy=true;
			ProgressStage.of(RouteUtil.mainStage, new Task<Void>() {
				@Override
				protected Void call() throws Exception {
					destroy();
					Platform.runLater(new Runnable() {
					    public void run() {
					    	RouteUtil.goIndex();
					    }
					});
					return null;
				}
			},"退出中...").show();
		}

	}

	public void next(ActionEvent event) {
		if(!isDestroy) {
			isDestroy=true;
			ProgressStage.of(RouteUtil.mainStage, new Task<Void>() {
				@Override
				protected Void call() throws Exception {
					destroy();
					Platform.runLater(new Runnable() {
					    public void run() {
					    	RouteUtil.goScanner();
					    }
					});
					return null;
				}
			},"前往扫码页面中...").show();
		}
	}
	
	public void setting(ActionEvent event) {
		if(!isDestroy) {
			isDestroy=true;
			Button bu = (Button) event.getSource();
			bu.setVisible(false);
			
			ProgressStage.of(RouteUtil.mainStage, new Task<Void>() {
				@Override
				protected Void call() throws Exception {
					destroy();
					RouteUtil.goConfig();
					return null;
				}
			},"前往设置页面中...").show();
		}
	}

	public void startCountDown() {
		animation = new Timeline(new KeyFrame(Duration.millis(1000), new EventHandler<ActionEvent>() {
			public void handle(ActionEvent event) {
				if(RouteUtil.getTime()>0) {
					RouteUtil.setTime(RouteUtil.getTime() - 1);
					if (RouteUtil.getTime() == 0) {
						timerLabel.setText("0");
						LayerUtil.open("操作超时！", 999);
					} else if (RouteUtil.getTime() > 0) {
						timerLabel.setText(RouteUtil.getTime() + "");
					}
				}
			}
		}));
		animation.setCycleCount(Timeline.INDEFINITE);
		animation.play();
	}

	public void destroy() {
		if (animation != null) {
			animation.stop();
		}
		if (rotateTransitionOut != null) {
			rotateTransitionOut.stop();
		}
		if (rotateTransitionIn != null) {
			rotateTransitionIn.stop();
		}
	}

	public boolean isDestroy() {
		return isDestroy;
	}

	public void setDestroy(boolean isDestroy) {
		this.isDestroy = isDestroy;
	}

}

class ArchivePanel extends Pane {
	private ArchiveDialog archiveDialog;
	public ArchivePanel(final ArchiveController controller,Store store,List<StoreMap> storeMaps) {
		this.setPrefSize(438.0, 313.0);
		this.setMaxSize(438.0, 313.0);
		this.setMinSize(438.0, 313.0);
		this.setId("archives-card");

		ImageView imageView = new ImageView();
		if(StrKit.equals(store.getStatus(), "-1")) {
			imageView.setImage(new Image(getClass().getResourceAsStream("/application/resources/overtime.png")));
		}
		else if (StrKit.equals(store.getStatus(), "0")){//预警
			imageView.setImage(new Image(getClass().getResourceAsStream("/application/resources/yujing.png")));
		}
		else if (StrKit.equals(store.getStatus(), "1")){//待审
			imageView.setImage(new Image(getClass().getResourceAsStream("/application/resources/待审.png")));
		}
		else if (StrKit.equals(store.getStatus(), "2")){//正常
			imageView.setImage(new Image(getClass().getResourceAsStream("/application/resources/正常.png")));
		}
		else if (StrKit.equals(store.getStatus(), "3")){//完成
			imageView.setImage(new Image(getClass().getResourceAsStream("/application/resources/完成.png")));
		}
		else {
			imageView.setImage(new Image(getClass().getResourceAsStream("/application/resources/fine.png")));
		}
		
		imageView.setX(378.812);
		imageView.setY(13.335);
		
		Button inBtn = new Button();
		inBtn.setLayoutX(10.998);
		inBtn.setLayoutY(249.665);
		inBtn.setPrefSize(118.0, 41.0);
		inBtn.setMaxSize(118.0, 41.0);
		inBtn.setMinSize(118.0, 41.0);
		inBtn.setId("archives-card-in-btn");
		inBtn.setAccessibleText(store.getId());
		inBtn.setOnAction(new EventHandler<ActionEvent>() {
			public void handle(ActionEvent event) {
				if(!controller.isDestroy()) {
					Button bu = (Button) event.getSource();
					ProgressStage.of(RouteUtil.mainStage, new Task<Void>() {
						@Override
						protected Void call() throws Exception {
							controller.setDestroy(true);
							controller.destroy();
							RouteUtil.goCabGroup(bu.getAccessibleText(), false);
							return null;
						}
					},"前往柜子组页面中...").show();
				}
			}
		});

//		Button authBtn=new Button();
//		authBtn.setLayoutX(159.07);
//		authBtn.setLayoutY(249.665);
//		authBtn.setPrefSize(118.0,41.0);
//		authBtn.setMaxSize(118.0,41.0);
//		authBtn.setMinSize(118.0,41.0);
//		authBtn.setId("archives-card-auth-btn");
//		authBtn.setOnAction(new EventHandler<ActionEvent>() {
//			public void handle(ActionEvent event) {
//				if(!controller.isDestroy()) {
//					Button bu = (Button) event.getSource();
//					ProgressStage.of(RouteUtil.mainStage, new Task<Void>() {
//						@Override
//						protected Void call() throws Exception {
//							controller.setDestroy(true);
//							controller.destroy();
//							RouteUtil.goAuthorize(bu.getAccessibleText());
//							return null;
//						}
//					},"前往卷宗授权页面中...").show();
//				}
//			}
//		});

		Button getBtn = new Button();
		getBtn.setLayoutX(306.0);
		getBtn.setLayoutY(249.66);
		getBtn.setPrefSize(118.0, 41.0);
		getBtn.setMaxSize(118.0, 41.0);
		getBtn.setMinSize(118.0, 41.0);
		getBtn.setId("archives-card-out-btn");
		getBtn.setAccessibleText(store.getId());

		getBtn.setOnAction(new EventHandler<ActionEvent>() {
			public void handle(ActionEvent event) {
				if(!controller.isDestroy()) {
					Button bu = (Button) event.getSource();
					ProgressStage.of(RouteUtil.mainStage, new Task<Void>() {
						@Override
						protected Void call() throws Exception {
							controller.setDestroy(true);
							controller.destroy();
							RouteUtil.goCabGroup(bu.getAccessibleText(), true);
							return null;
						}
					},"前往卷宗提取页面中...").show();
				}
			}
		});

		this.getChildren().add(imageView);
		this.getChildren().add(inBtn);
		//this.getChildren().add(authBtn);
		this.getChildren().add(getBtn);
		
		if(storeMaps!=null && storeMaps.size()>0) {
			for (int j = 0; j < storeMaps.size(); j++) {
				Label fieldLabel = new Label();
				fieldLabel.setPrefSize(110.0, 32.0);
				fieldLabel.setMaxSize(110.0, 32.0);
				fieldLabel.setMinSize(110.0, 32.0);
				fieldLabel.setLayoutX(23.0);
				fieldLabel.setLayoutY(21 + (j * 35));
				fieldLabel.setText(storeMaps.get(j).getColumnLabel());
				fieldLabel.setId("archives-card-Label");

				
				Label fieldValue = new Label();
				fieldValue.setPrefSize(296.0, 32.0);
				fieldValue.setMaxSize(296.0, 32.0);
				fieldValue.setMinSize(296.0, 32.0);
				fieldValue.setLayoutX(110.0);
				fieldValue.setLayoutY(21 + (j * 35));
				fieldValue.setText(store.getStr(storeMaps.get(j).getColumnValue()));
				fieldValue.setId("archives-card-Label");
				if(StrKit.equals("1",storeMaps.get(j).getClick())) {
					fieldValue.setOnMouseClicked(new EventHandler<Event>() {
						@Override
						public void handle(Event event) {
							if(archiveDialog!=null) {
								archiveDialog.close();
								archiveDialog=null;
							}
							Platform.runLater(new Runnable() {
							    public void run() {
									ProgressStage.of(RouteUtil.mainStage, new Task<Void>() {
										@Override
										protected Void call() throws Exception {
											try {
												if(ShiroUtil.getConfig()==null || StrKit.isBlank(ShiroUtil.getConfig().getSynURL())) {
													throw new Exception("请先设置查询接口！");
												}
												HttpClientResult httpClientResult=HttpUtil.doGet(String.format("%s/api/archive/getById?cabinetId=%s&id=%s", ShiroUtil.getConfig().getSynURL(),ShiroUtil.getAuth(),store.getId()));
												if(httpClientResult==null) {
													throw new Exception("请求异常！");
												}
												if(httpClientResult.getCode()!=200) {
													throw new Exception("请求异常！");
												}
												String content=httpClientResult.getContent();
												if(StrKit.isBlank(content)) {
													throw new Exception("无响应！");
												}
												JSONObject jsonObject=JSONObject.fromObject(content);
												if(jsonObject==null) {
													throw new Exception("无响应！");
												}
												if(jsonObject.has("code")) {
													int code=jsonObject.getInt("code");
													if(code!=200) {
														throw new Exception(jsonObject.getString("message"));
													}
													if(jsonObject.has("data")) {
														String data=jsonObject.getString("data");
														if(StrKit.isBlank(data)) {
															throw new Exception("未查询到数据！");
														}
														JSONObject dataObject=JSONObject.fromObject(data);
														if(dataObject==null) {
															throw new Exception("未查询到数据！");
														}
														Archive archive=(Archive) JSONObject.toBean(dataObject, Archive.class);
														if(archive==null) {
															throw new Exception("数据异常！");
														}
														Platform.runLater(new Runnable() {
														    public void run() {
																archiveDialog=new ArchiveDialog(RouteUtil.mainStage,archive);
														    }
														});
														return null;
													}else {
														throw new Exception("无数据返回！");
													}
												}else {
													throw new Exception("数据不完整！");
												}
											}catch (Exception e) {
												Platform.runLater(new Runnable() {
												    public void run() {
												    	LayerUtil.open(e.getMessage(), 500);
												    }
												});
											}
											return null;
										}
									},"查询中...").show();
							    }
							});
							
						}
					});
				}
				this.getChildren().add(fieldLabel);
				this.getChildren().add(fieldValue);
			}
		}else {
			for (int j = 0; j < 5; j++) {
				Label fieldLabel = new Label();
				fieldLabel.setPrefSize(110.0, 32.0);
				fieldLabel.setMaxSize(110.0, 32.0);
				fieldLabel.setMinSize(110.0, 32.0);
				fieldLabel.setLayoutX(23.0);
				fieldLabel.setLayoutY(21 + (j * 35));
				fieldLabel.setText("field"+(j+1)+":");
				fieldLabel.setId("archives-card-Label");

				Label fieldValue = new Label();
				fieldValue.setPrefSize(296.0, 32.0);
				fieldValue.setMaxSize(296.0, 32.0);
				fieldValue.setMinSize(296.0, 32.0);
				fieldValue.setLayoutX(110.0);
				fieldValue.setLayoutY(21 + (j * 35));
				fieldValue.setText(store.getStr("field"+(j+1)));
				fieldValue.setId("archives-card-Label");
				this.getChildren().add(fieldLabel);
				this.getChildren().add(fieldValue);
			}
		}
		
		
	}
}
